package com.sws.orderMS.command.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sws.orderMS.OrderMSApplication;
import com.sws.orderMS.OrderMSDao;
import com.sws.orderMS.command.UserCommand;
import com.sws.orderMS.pojo.Client;
import com.sws.orderMS.pojo.Order;
import com.sws.orderMS.pojo.OrderItem;
import com.sws.orderMS.pojo.Product;
import com.sws.orderMS.pojo.ShoppingCart;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class OrderCommand extends UserCommand {
	
	public OrderCommand(User userProfile) {
		super(userProfile);
	}

	@Override
	public void execute() {
		Client client = (Client)userProfile;
		if (client.getMyShoppingCart() == null) {			// 如果我的购物车对象未创建,则进行一些初始化操作,保证我的购物车是单例的
			client.setMyShoppingCart(new ShoppingCart());
			client.getMyShoppingCart().setOrderlist(new ArrayList<OrderItem>());
		}
		OrderMSDao dao = new OrderMSDao();
		
		while (true) {
			String productCode = Tool.askUserInputNotNull("请输入需要订购的商品代号:");
			Product product = dao.searchProductByCode(productCode);
			if (product == null) {
				Tool.printMsg("抱歉, 该商品不存在, 你可以使用list_product命令来查看可以订购的商品");
				return;
			}
			OrderItem orderItem = new OrderItem();
			int qty = product.getQty();
			String amountStr = Tool.askUserInputNotNull("请输入订购数量:");
			if (!isValidInput(amountStr)) {
				Tool.printMsg("Invalid input!");
				return;
			}
			int amount = Integer.parseInt(amountStr);
			while (amount > qty) {
				Tool.printMsg("当前订购数量超过该商品的库存数量, 请重新输入");
				amountStr = Tool.askUserInputNotNull("请输入订购数量:");
				if (!isValidInput(amountStr)) {
					Tool.printMsg("Invalid input!");
					return;
				}
				amount = Integer.parseInt(amountStr);
			}
			qty = qty - amount;
			product.setQty(qty);
			String memo = Tool.askUserInputNotNull("备注:");
			orderItem.setProduct(product);
			orderItem.setAmount(amount);
			orderItem.setMemo(memo);
			client.getMyShoppingCart().addItem(orderItem);
			Tool.printMsg("添加商品至购物车成功!当前我的购物车内有" + client.getMyShoppingCart().getItemNum() + "件商品");
			String command = Tool.askUserInputNotNull("你可以输入list来查看我的购物车或者输入Y|N选择是否继续订购");
			if ("list".equalsIgnoreCase(command)) {
				showMyShoppingCart(client.getMyShoppingCart());
				String commandInner = Tool.askUserInputNotNull("输入back返回继续订购,输入N停止订购");
				if ("N".equalsIgnoreCase(commandInner)) {
					break;
				}
				if ("back".equalsIgnoreCase(commandInner)) {
					continue;
				}
			}
			if ("N".equalsIgnoreCase(command)) {
				break;
			}
		}
		Order order = new Order();
		order.setMemo(null);
		order.setOrderList(client.getMyShoppingCart().getOrderList());
		if (!order.getOrderList().isEmpty()) {
			showOrder(order);
			double total = order.getTotal();
			double own = client.getWallet().getBalance();
			String confirmPay = Tool.askUserInputNotNull("提交订单? Y|N");
			if ("Y".equalsIgnoreCase(confirmPay)) {
				long orderNo = OrderMSApplication.getOrderNo();
				order.setOrderNo(String.valueOf(orderNo));
				order.setTimeStamp(new Timestamp(new Date().getTime()));
				for (int i = 0; i < order.getOrderList().size(); i++) {
					order.getOrderList().get(i).setItemNo(String.valueOf(orderNo + i + 1));
				}
				order.setCurrentStatus(1);
				order.setCurrentPaymentStatus(1);
				client.setMyShoppingCart(new ShoppingCart());	// 刷新购物车内容
				dao.insertOrder(order, client);
				String payType = Tool.askUserInputNotNull("请选择付款方式 (Alipay|Wechat|Unionpay):");
				client.getWallet().initMap();
				order.setPaymentMethodId(client.getWallet().getPaymentMethodId(payType));
				dao.insertPayment(order);
				
				String toPay = Tool.askUserInputNotNull("确认支付？Y|N");
				if ("Y".equalsIgnoreCase(toPay)) {
					if (total > own) {	// 余额不足
						order.setCurrentPaymentStatus(3);
						Tool.printMsg("抱歉, 您的账户余额不足！请先进行充值");
						dao.updatePayment(order);
						return;
					} else {
						order.setCurrentPaymentStatus(2);
						dao.updatePayment(order);	// 更新支付状态
						dao.updateInventory(order);	// 更新库存
						dao.updateUserBalance(own - total, client.getId());	// 更新账户余额
						client.getWallet().setBalance(own - total);
						dao.updateOrderStatuss(4, order);	// 更新支付状态
						Tool.printMsg("支付成功!");
					} 
				} else {	// 取消付款
					order.setCurrentPaymentStatus(1);
					dao.updatePayment(order);
				}
			} else {
				// 取消订单
				order.setTimeStamp(new Timestamp(new Date().getTime()));
				order.setCurrentStatus(2);
				dao.insertOrder(order, client);
			}
		} else {
			Tool.printMsg("您未订购任何商品!");
			return;
		}
	}

	public boolean isValidInput(String input) {
		Pattern pattern = Pattern.compile("[^0-9]");
		Matcher matcher = pattern.matcher(input.trim());
		if (matcher.find()) {
			return false;
		}
		return true;
	}
	
	public void showMyShoppingCart(ShoppingCart shoppingCart) {
		Tool.printMsg("我的购物车信息:");
		for (OrderItem orderItem: shoppingCart.getOrderList()) {
			Tool.printMsg(orderItem.toString());
		}
	}
	
	public void showOrder(Order order) {
		double total = 0;
		Tool.printMsg("以下是本订单详细信息:");
		for (OrderItem orderItem: order.getOrderList()) {
			Tool.printMsg(orderItem.toString());
			total = total + orderItem.getMoney();
		}
		order.setTotal(total);
		Tool.printMsg("合计:" + order.getTotal() + "元");
	}
	
}
